<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <link href="css/mui.css" rel="stylesheet"/>
    <style>
        html,
        body {
            height: 100%;
        }

        .mui-content {
            height: 100%;
            overflow: auto;
        }

        .red-point {
            position: relative;
        }

        .red-point::before {
            content: " ";
            border: 5px solid #C9394A; /*设置红色*/
            border-radius: 5px; /*设置圆角*/
            position: absolute;
            z-index: 3000;
            right: 0%;
            margin-right: -10px;
            margin-top: 0px;
        }
    </style>
</head>

<body>
<div class="mui-content" id="showData">
    <ul class="mui-table-view" id="ul_friend_request_list" style="margin-bottom: 10px;">

    </ul>
    <ul id="ul_chatSnapshot" class="mui-table-view">
        <li class="mui-table-view-cell mui-media">
            <!-- <div class="mui-slider-right mui-disabled">
                 <a class="mui-btn mui-btn-red">删除</a>
             </div>-->
            <div class="friend-with-Snapshot mui-slider-handle mui-media-body">
                <img class="mui-media-object mui-pull-left" src="image/face-default-cat.png"/>
                <span class="red-point">123</span>
                <p class="mui-ellipsis">这里是聊天内容...</p>
            </div>
        </li>

    </ul>
</div>
<script src="js/app.js"></script>
<script src="js/mui.js"></script>
<script type="text/javascript">
    mui.init();
    mui.plusReady(function () {

        //显示好友请求
        ShowData();
        //启动web socket
        CHAT.init();
        //渲染聊天快照
        loadingChatSnapshot();

        //加载好友请求记录
        var thisWebview = plus.webview.currentWebview();
        thisWebview.addEventListener("show", function () {
            //显示好友请求
            ShowData();
            //渲染聊天快照
            loadingChatSnapshot();
        });

        //添加自定义事件,刷新头像,退出时调用
        window.addEventListener("refresh", function () {
            clearData();
        });

        //重新加载好友请求记录
        window.addEventListener("reloadRequest", function () {
            ShowData();
        });

        //重新渲染聊天快照
        window.addEventListener("reloadChatSnapshot", function () {
            console.log("触发重新渲染聊天快照");
            //渲染聊天快照
            loadingChatSnapshot();
        });

        //添加自定义事件,初始化链接
        window.addEventListener("openWebSocket", function () {
            //启动web socket
            CHAT.init();
        });


    });

    //渲染展示聊天快照
    function loadingChatSnapshot() {
        console.log("开始渲染聊天快照");
        //获取用户信息
        var userInfo = app.getUserGlobalInfo();
        //获取聊天快照
        var chatSnapshotList = app.getUserChatSnapshot(userInfo.id);

        //获取元素
        var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
        ul_chatSnapshot.innerHTML = "";
        //遍历聊天快照列表
        for (var i = 0; i < chatSnapshotList.length; i++) {
            var chatSnapshot = chatSnapshotList[i];
            //根据朋友id 获取用户信息
            var friendInfo = app.getFriendInfoById(chatSnapshot.friendId);
            var faceImg = "";
            if (app.isNotNull(friendInfo.faceImage)) {
                faceImg = app.imgServerUrl + friendInfo.faceImage;
            } else {
                faceImg = "image/face.jpeg";
            }
            //未读消息提示
            var red_point = "";
            if (chatSnapshot.isRead!=true){
                red_point="red-point";
            }

            //拼接
            var chatItemHtml = '<li class="mui-table-view-cell mui-media">' +
                '<div class="friend-with-Snapshot mui-slider-handle mui-media-body" ' +
                'friendUserId="' + friendInfo.id + '" ' +
                'friendNickname="' + friendInfo.nickname + '" ' +
                'friendFaceImage="' + friendInfo.faceImage + '">' +
                '<img class="mui-media-object mui-pull-left" src="' + faceImg + '"/>' +
                '<span class="'+red_point+'">' + friendInfo.nickname + '</span>' +
                '<p class="mui-ellipsis">' + chatSnapshot.msg + '</p>' +
                ' </div>' +
                ' </li>';
            console.log("拼接的聊天快照内容 : " + chatItemHtml);
            //快照渲染到页面最底部
            ul_chatSnapshot.insertAdjacentHTML("beforeend", chatItemHtml);
        }

        // 为好友通讯录批量绑定点击事件
        mui("#ul_chatSnapshot").on("tap", ".friend-with-Snapshot", function (e) {
            var friendUserId = this.getAttribute("friendUserId");
            var friendNickname = this.getAttribute("friendNickname");
            var friendFaceImage = this.getAttribute("friendFaceImage");

            // 打开聊天子页面
            mui.openWindow({
                url: "chatting.html",
                id: "chatting-" + friendUserId,	// 每个朋友的聊天页面都是唯一对应的
                extras: {
                    friendUserId: friendUserId,
                    friendNickname: friendNickname,
                    friendFaceImage: friendFaceImage
                }
            });

        })
    }


    //启动websocket
    window.CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                //判断是否已经链接过,如果链接过则不重复初始化
                if (CHAT.socket != null && CHAT.socket != undefined && CHAT.socket.readyState == WebSocket.OPEN) {
                    console.log("websocket 重复初始化");
                    return false;
                }
                console.log("websocket 进行初始化");
                CHAT.socket = new WebSocket(app.webSocketServerUrl);
                CHAT.socket.onopen = CHAT.wsopen;
                CHAT.socket.onclose = CHAT.wsclose;
                CHAT.socket.onerror = CHAT.wserror;
                CHAT.socket.onmessage = CHAT.getedMsg;
            } else {
                alert("浏览器不支持websocket协议...");
            }
        },
        chat: function (msg) {
            //判断是否已经链接过,如果链接过则不重复初始化
            if (CHAT.socket != null && CHAT.socket != undefined && CHAT.socket.readyState == WebSocket.OPEN) {


                //重启后再次发送消息
                console.log("发送 web socket 消息 : " + msg);
                CHAT.socket.send(msg);
                //重新渲染聊天快照信息
                loadingChatSnapshot();
            } else {
                //重新启动web socket
                CHAT.init();
                console.log("断线重连");
                //等待一秒后再次执行此方法 判断状态 重新发送消息
                setTimeout("CHAT.repeatSend('" + msg + "')", "1000");
            }
        },
        repeatSend: function (msg) {
            //重启后再次发送消息
            console.log("断线重连发送 web socket 消息 : " + msg);
            CHAT.socket.send(msg);
            //重新渲染聊天快照信息
            loadingChatSnapshot();
        },
        wserror: function () {
            console.log("web socket链接 发生错误")
        },
        wsclose: function () {
            console.log("web socket链接 已关闭")
        },
        wsopen: function () {
            console.log("web socket链接 已建立");
            var userInfo = app.getUserGlobalInfo();
            //构建chatMsg
            var chatMsg = new app.ChatMsg(userInfo.id, null, null, null);
            //构建dataContent
            var dataContent = new app.DataContent(app.CONNECT, chatMsg, null);
            //发送web socket
            CHAT.chat(JSON.stringify(dataContent));
            //定时发送心跳 10秒发送一次
            setInterval("CHAT.keepalive()",10000)
        },
        getedMsg: function (result) {
            console.log("web socket链接 接受到消息 : " + result.data);

            var dataContent = JSON.parse(result.data);
            var action = dataContent.action;
            if (app.CHAT === action) {
                console.log("消息类型属于聊天 222");
                var chatMsg = dataContent.chatMsg;
                var senderId = chatMsg.senderId;
                //获取chart list 的webview 发送消息
                var chatting = plus.webview.getWebviewById("chatting-" + senderId);
                //用于设置聊天快照的已读未读
                var isRead = true;
                if (chatting != null) {
                    console.log("chatting不等于空 开始渲染消息");
                    //渲染
                    chatting.evalJS("getMsg('" + chatMsg.msg + "')");
                    //重排序
                    chatting.evalJS("resizeScreen()");
                } else {
                    //todo 未打开webview逻辑待完成
                    //没有webview的话则是未读快照
                    isRead = false;
                }

                //保存聊天快照
                app.saveUserChatSnapshot(chatMsg.receiverId, senderId, chatMsg.msg, isRead);
                //签收
                var dataContentSign = new app.DataContent(app.SIGNED, null, chatMsg.msgId);
                //发送
                CHAT.chat(JSON.stringify(dataContentSign));
                //保存聊天记录
                app.saveUserChatHistory(chatMsg.receiverId, senderId, chatMsg.msg, 2,true,chatMsg.msgId);
                //重新渲染聊天快照
                loadingChatSnapshot();

                //拉取好友信息
            } else if (app.PULL_FRIEND === action) {
                console.log("好友邀请通过,接受到服务器通知拉取最新好友信息");
                var Contacts = plus.webview.getWebviewById("chart-Contacts.html");
                mui.fire(Contacts, "refresh");
                return false;
            }


            /* var chatting = plus.webview.getWebviewById("chatting-181227F15Z0HSAY8");
             chatting.evalJS("getMsg('" + result + "')");*/
        },
        keepalive: function () {
            //构建心跳对象
            var dataContent = new app.DataContent(app.KEEPALIVE,null,"ping");
            //发送
            CHAT.chat(JSON.stringify(dataContent));
        }
    };

    function ShowData() {
        //获取用户全局变量
        var userInfo = app.getUserGlobalInfo();
        console.log("获取本地变量");
        console.log(JSON.stringify(userInfo));
        loadFriendRequest(userInfo);
    }

    function loadFriendRequest(userInfo) {
        console.log("发送ajax拉取好友请求信息 用户id为 : " + userInfo.id);
        mui.ajax(app.serverUrl + "/user/getFriendRequest", {
            data: {
                acceptUserId: userInfo.id
            },
            dataType: 'json',//服务器返回json格式数据
            type: 'post',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒；
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            success: function (data) {
                //服务器返回响应，根据响应结果，分析是否登录成功；
                console.log("好友请求 返回结果");
                console.log(JSON.stringify(data.data));

                var ul_friend_request_list = document.getElementById("ul_friend_request_list");
                //判断状态
                if (data.status == 200) {
                    var result = data.data;
                    var appendHtml = "";
                    for (var i = 0; i < result.length; i++) {
                        appendHtml += readLineData(result[i]);
                    }

                    if (app.isNotNull(appendHtml)) {
                        console.log("appendHtml进入if分支");
                        console.log(JSON.stringify(appendHtml));
                        ul_friend_request_list.innerHTML = appendHtml;
                        //结果生成完毕后开始绑定事件
                        //忽略请求
                        mui(".btnOper").on("tap", ".ignoreRequest", function () {
                            var friendId = this.getAttribute("friendId");
                            ignoreRequest(friendId, userInfo);
                        });
                        //同意好友请求
                        mui(".btnOper").on("tap", ".passRequest", function () {
                            var friendId = this.getAttribute("friendId");
                            passRequest(friendId, userInfo);
                        });
                    } else {
                        ul_friend_request_list.innerHTML = "";
                        console.log("appendHtml进入else分支");
                        console.log(JSON.stringify(appendHtml));
                    }
                } else {
                    ul_friend_request_list.innerHTML = "";
                    app.showToast(data.msg, "error");
                    return false;
                }
            }
        });
    }

    function readLineData(friend) {
        var img = "";
        if (app.isNotNull(friend.sendFaceImage)) {
            img = app.imgServerUrl + friend.sendFaceImage;
        } else {
            img = "image/face.jpeg";
        }
        html = '<li class="btnOper mui-table-view-cell mui-media">' +
            '<a href="javascript:;">' +
            '<img class="mui-media-object mui-pull-left" src="' + img + '">' +
            '<span id="span_nickname" class="mui-pull-right">' +
            '<button friendId="' + friend.id + '" type="button" class="ignoreRequest mui-btn mui-btn-grey" style="padding: 4px 10px;margin-right:5px;">忽略</button>' +
            '<button friendId="' + friend.id + '" type="button" class="passRequest mui-btn mui-btn-danger" style="padding: 4px 10px;">通过</button>' +
            '</span>' +
            '<div class="mui-media-body">' +
            '<label>' + friend.sendNickName + '</label>' +
            '<p class="mui-ellipsis">请求添加你为朋友</p>' +
            '</div>' +
            '</a>' +
            '</li>';

        return html;
    }

    //忽略好友请求
    function ignoreRequest(friendId, userInfo) {
        mui.ajax(app.serverUrl + "/friend/dropFriendRequest", {
            data: {
                acceptUserId: userInfo.id,
                sendUserId: friendId
            },
            dataType: 'json',//服务器返回json格式数据
            type: 'post',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒；
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            success: function (data) {
                //服务器返回响应，根据响应结果，分析是否登录成功；
                console.log(JSON.stringify(data));

                //判断状态
                if (data.status == 200) {
                    //如果请求成功则刷新信息
                    loadFriendRequest(userInfo);
                } else {
                    app.showToast(data.msg, "error");
                    return false;
                }
            }
        });
    }

    //通过好友请求
    function passRequest(friendId, userInfo) {
        mui.ajax(app.serverUrl + "/friend/acceptFriendRequest", {
            data: {
                acceptUserId: userInfo.id,
                sendUserId: friendId
            },
            dataType: 'json',//服务器返回json格式数据
            type: 'post',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒；
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            success: function (data) {
                //服务器返回响应，根据响应结果，分析是否登录成功；
                console.log(JSON.stringify(data));

                //判断状态
                if (data.status == 200) {
                    //如果请求成功则刷新信息
                    loadFriendRequest(userInfo);
                } else {
                    app.showToast(data.msg, "error");
                    return false;
                }
            }
        });
    }

    function clearData() {
        var ul_friend_request_list = document.getElementById("ul_friend_request_list");
        if (ul_friend_request_list.innerHTML != null) {
            ul_friend_request_list.innerHTML = "";
        }

        console.log("web socket 关闭连接");
        CHAT.socket.close();
    }

</script>
</body>

</html>
